// 全局变量
let originalImage = null;
let pageImages = [];

// DOM元素
const uploadArea = document.getElementById('uploadArea');
const imageInput = document.getElementById('imageInput');
const loading = document.getElementById('loading');
const previewSection = document.getElementById('previewSection');
const previewContainer = document.getElementById('previewContainer');
const pageInfo = document.getElementById('pageInfo');
const resetBtn = document.getElementById('resetBtn');
const downloadBtn = document.getElementById('downloadBtn');
const layoutOptions = document.getElementsByName('layout');
const progressText = document.getElementById('progressText');
const progressBar = document.getElementById('progressBar');
const progressFill = document.getElementById('progressFill');
const overlapCheckbox = document.getElementById('enableOverlap');
const overlapSlider = document.getElementById('overlapSlider');
const overlapValue = document.getElementById('overlapValue');

// A4尺寸（以像素为单位，300 DPI）
const A4_WIDTH = 2480;
const A4_HEIGHT = 3508;

// 事件监听器
uploadArea.addEventListener('click', () => imageInput.click());
uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.style.backgroundColor = '#e1f0fa';
});
uploadArea.addEventListener('dragleave', () => {
    uploadArea.style.backgroundColor = '#f8fafc';
});
uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.style.backgroundColor = '#f8fafc';
    
    if (e.dataTransfer.files.length > 0) {
        handleImageUpload(e.dataTransfer.files[0]);
    }
});

imageInput.addEventListener('change', (e) => {
    if (e.target.files.length > 0) {
        handleImageUpload(e.target.files[0]);
    }
});

resetBtn.addEventListener('click', resetApp);
downloadBtn.addEventListener('click', generatePDF);

// 监听选项变化
layoutOptions.forEach(option => {
    option.addEventListener('change', () => {
        if (originalImage) {
            processImage();
        }
    });
});

overlapCheckbox.addEventListener('change', () => {
    if (originalImage) {
        processImage();
    }
});

overlapSlider.addEventListener('input', () => {
    overlapValue.textContent = overlapSlider.value;
    if (originalImage) {
        processImage();
    }
});

// 处理图片上传
function handleImageUpload(file) {
    // 检查文件类型
    if (!file.type.match('image/jpeg') && !file.type.match('image/png')) {
        alert('请上传 JPG 或 PNG 格式的图片！');
        return;
    }
    // 检查文件大小（50MB限制）
    if (file.size > 50 * 1024 * 1024) {
        alert('图片大小不能超过 50MB！');
        return;
    }
    
    // 显示加载状态
    loading.style.display = 'block';
    uploadArea.style.display = 'none';
    
    const reader = new FileReader();
    
    reader.onload = function(e) {
        const img = new Image();
        
        img.onload = function() {
            originalImage = img;
            processImage();
        };
        
        img.src = e.target.result;
    };
    
    reader.readAsDataURL(file);
}

// 处理图片分页 - 简化可靠的算法
function processImage() {
    pageImages = [];
    
    progressBar.style.display = 'block';
    progressText.style.display = 'block';
    updateProgress(0);
    
    const layout = document.querySelector('input[name="layout"]:checked').value;
    const useOverlap = overlapCheckbox.checked;
    const overlapHeight = parseInt(overlapSlider.value);
    
    let scale, drawWidth, drawHeight, offsetX, offsetY;
    
    if (layout === 'fitWidth') {
        scale = A4_WIDTH / originalImage.width;
        drawWidth = A4_WIDTH;
        drawHeight = originalImage.height * scale;
        offsetX = 0;
        offsetY = 0;
    } else {
        scale = A4_HEIGHT / originalImage.height;
        drawWidth = originalImage.width * scale;
        drawHeight = A4_HEIGHT;
        offsetX = (A4_WIDTH - drawWidth) / 2;
        offsetY = 0;
    }
    
    // 计算分页位置 - 使用简单可靠的方法
    const scaledHeight = originalImage.height * scale;
    const pageBreaks = [];
    
    if (!useOverlap) {
        // 无重叠：简单分页
        for (let y = 0; y < scaledHeight; y += A4_HEIGHT) {
            pageBreaks.push({
                startY: y,
                endY: Math.min(y + A4_HEIGHT, scaledHeight)
            });
        }
    } else {
        // 有重叠：确保内容完整
        let currentY = 0;
        while (currentY < scaledHeight) {
            let pageEndY = currentY + A4_HEIGHT;
            
            // 如果是最后一页，直接到结尾
            if (pageEndY >= scaledHeight) {
                pageBreaks.push({
                    startY: currentY,
                    endY: scaledHeight
                });
                break;
            }
            
            // 当前页包含重叠区域
            pageBreaks.push({
                startY: currentY,
                endY: Math.min(pageEndY + overlapHeight, scaledHeight)
            });
            
            // 下一页从当前页的结束位置减去重叠区域开始
            currentY = pageEndY;
        }
    }
    
    const totalPages = pageBreaks.length;
    
    // 创建Canvas进行图片分割
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    canvas.width = A4_WIDTH;
    canvas.height = A4_HEIGHT;
    
    // 为每一页创建图片
    for (let i = 0; i < totalPages; i++) {
        const pageBreak = pageBreaks[i];
        
        // 清除画布并设置白色背景
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, A4_WIDTH, A4_HEIGHT);
        
        if (layout === 'fitWidth') {
            const sourceStartY = pageBreak.startY / scale;
            const sourceHeight = (pageBreak.endY - pageBreak.startY) / scale;
            const displayHeight = Math.min(A4_HEIGHT, pageBreak.endY - pageBreak.startY);
            
            ctx.drawImage(
                originalImage,
                0, sourceStartY, originalImage.width, sourceHeight,
                0, 0, drawWidth, displayHeight
            );
        } else {
            const sourceStartY = pageBreak.startY / scale;
            const sourceHeight = (pageBreak.endY - pageBreak.startY) / scale;
            
            ctx.drawImage(
                originalImage,
                0, sourceStartY, originalImage.width, sourceHeight,
                offsetX, offsetY, drawWidth, drawHeight
            );
        }
        
        // 将画布内容转换为数据URL
        const pageDataURL = canvas.toDataURL('image/jpeg', 0.9);
        pageImages.push(pageDataURL);
        
        // 更新进度
        updateProgress(((i + 1) / totalPages) * 100);
    }
    
    // 隐藏加载状态和进度条，显示预览
    loading.style.display = 'none';
    progressBar.style.display = 'none';
    progressText.style.display = 'none';
    previewSection.style.display = 'block';
    
    // 更新页面信息
    const overlapInfo = useOverlap ? `（重叠保护：${overlapHeight}像素）` : '';
    pageInfo.innerHTML = `图片将被分为 <strong>${totalPages}</strong> 页 A4 尺寸的PDF ${overlapInfo}`;
    
    // 显示预览
    renderPreviews();
}

// 更新进度条
function updateProgress(percent) {
    progressFill.style.width = percent + '%';
    progressText.textContent = `处理进度: ${Math.round(percent)}%`;
}

// 渲染预览图
function renderPreviews() {
    previewContainer.innerHTML = '';
    
    // 只显示前12页预览以避免性能问题
    const previewCount = Math.min(pageImages.length, 12);
    
    for (let i = 0; i < previewCount; i++) {
        const previewItem = document.createElement('div');
        previewItem.className = 'preview-item';
        
        // 设置预览图尺寸（缩小以便显示）
        const previewWidth = 200;
        const previewHeight = (A4_HEIGHT / A4_WIDTH) * previewWidth;
        
        previewItem.innerHTML = `
            <img src="${pageImages[i]}" class="preview-img" style="width: ${previewWidth}px; height: ${previewHeight}px;">
            <div class="preview-label">第 ${i + 1} 页</div>
        `;
        
        previewContainer.appendChild(previewItem);
    }
    
    // 如果总页数超过预览数量，显示提示
    if (pageImages.length > previewCount) {
        const infoText = document.createElement('div');
        infoText.style.textAlign = 'center';
        infoText.style.width = '100%';
        infoText.style.color = '#7f8c8d';
        infoText.style.marginTop = '10px';
        infoText.textContent = `... 还有 ${pageImages.length - previewCount} 页未显示`;
        previewContainer.appendChild(infoText);
    }
}

// 生成PDF
function generatePDF() {
    if (pageImages.length === 0) {
        alert('请先上传图片！');
        return;
    }
    
    // 显示加载状态
    loading.style.display = 'block';
    progressBar.style.display = 'block';
    progressText.style.display = 'block';
    updateProgress(0);
    
    // 使用setTimeout确保UI更新
    setTimeout(() => {
        try {
            // 创建PDF实例
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF({
                orientation: 'portrait',
                unit: 'px',
                format: [A4_WIDTH, A4_HEIGHT]
            });
            
            // 添加每一页到PDF
            pageImages.forEach((imgSrc, index) => {
                if (index > 0) {
                    pdf.addPage();
                }
                
                // 添加图片到PDF页面
                pdf.addImage(imgSrc, 'JPEG', 0, 0, A4_WIDTH, A4_HEIGHT);
                
                // 更新进度
                updateProgress(((index + 1) / pageImages.length) * 100);
            });
            
            // 保存PDF
            pdf.save('长图转换PDF.pdf');
            
        } catch (error) {
            console.error('生成PDF时出错:', error);
            alert('生成PDF时出现错误，请重试或更换图片。');
        } finally {
            // 隐藏加载状态
            loading.style.display = 'none';
            progressBar.style.display = 'none';
            progressText.style.display = 'none';
        }
    }, 500);
}

// 重置应用
function resetApp() {
    originalImage = null;
    pageImages = [];
    imageInput.value = '';
    previewSection.style.display = 'none';
    uploadArea.style.display = 'block';
    loading.style.display = 'none';
    progressBar.style.display = 'none';
    progressText.style.display = 'none';
}